import { Injectable } from '@angular/core';
import { CommHttpService } from '../../../core/comm.http.service';
import { HttpService } from '../../../core/http.service';
import { SERVERS_NAME } from '../../../config/config';
import { Response } from '../../../core/domain/response';
import { Observable } from 'rxjs';
import { Auth } from './domain/auth';
import { PageEntity } from '../../../core/domain/page.entity';

@Injectable()
export class RolesService extends CommHttpService {

  protected preUrl = `${SERVERS_NAME.SECURITY_SERVER}sys/role/`;

  constructor(protected http: HttpService) {
    super(http);
  }

  /**
   * 获取级联选择树
   */
  setAuth(id: string, modelTree: Auth[]): Observable<Response> {
    return this.http.post({roleId: id, moduleIds: this.getModuleIds(modelTree)}, this.preUrl + 'auth');
  }

  /**
   * 根据角色Id获取已有权限Id
   */
  viewAuth(key: string): Observable<Response> {
    return this.http.post({id: key}, this.preUrl + 'viewAuth');
  }

  /**
   * 根据用户角色查询已分配此角色用户
   * @param  roleId 角色Id
   */
  queryUserAuth(roleId: string): Observable<Response> {
    return this.http.post({id: roleId}, this.preUrl + 'queryUserAuth');
  }

  /**
   * 根据用户角色查询未分配此角色用户
   * @param  roleId 角色Id
   * @param pageInfo 分页查询条件
   */
  pageQueryUser(pageInfo: PageEntity, roleId: string): Observable<Response> {
    pageInfo.filters['roleId'.toString()] = {
      value: roleId,
      matchMode: 'equals'
    };
    return this.http.post(pageInfo, this.preUrl + 'pageQueryUser');
  }

  /**
   * 根据用户角色查询未分配此角色用户
   * @param  roleId 角色Id
   * @param userIdList 选中的用户Id
   */
  userAuth(roleId: string, userIdList: string[]): Observable<Response> {
    return this.http.post({roleId, userIdList}, this.preUrl + 'assignUser');
  }

  /**
   * 移除具有当前角色的用户
   */
  deleteAuth(roleId: string, userIdsArr: string[]): Observable<Response> {
    return this.http.post({roleIds: [roleId], userIds: userIdsArr}, this.preUrl + 'deleteAuth');
  }

  /**
   * 获取所有选中节点id
   * @param modelTree 菜单树
   */
  getModuleIds(modelTree: Auth[]): string[] {
    const moduleIds: string[] = [];
    const getModuleIdArr = (treeList) => {
      treeList.forEach(item => {
        if (item.checked) {
          moduleIds.push(item.key);
        }
        if (item.children.length) {
          getModuleIdArr(item.children);
        } else {
          return;
        }
      });
    };
    getModuleIdArr(modelTree);
    return moduleIds;
  }
}
